"""CLI入口模块"""

import asyncio
import typer
import json
from pathlib import Path
from typing import Optional

from .config import ConfigManager
from .scanner import create_scanner
from .logging_config import setup_logging
from .douyin_exporter import export_emby_library_to_douyin_json, create_emby_client_from_credentials

app = typer.Typer(
    name="embytools",
    help="Emby服务器自动化管理工具",
    add_completion=False
)

config_manager = ConfigManager()


@app.command()
def init(
    config_path: Optional[str] = typer.Option(
        None,
        help="配置文件路径，默认使用 config/config.yaml"
    )
):
    """初始化配置文件"""
    try:
        target_path = config_manager.create_sample_config(config_path)
        typer.echo(f"✅ 示例配置文件已创建: {target_path}")
        typer.echo("📝 请编辑配置文件，设置正确的Emby服务器信息")
    except Exception as e:
        typer.echo(f"❌ 创建配置文件失败: {e}", err=True)
        raise typer.Exit(1)


@app.command()
def test_conn():
    """测试Emby服务器连接"""
    try:
        config = config_manager.get_config()
        typer.echo(f"🔌 测试连接服务器: {config.server.host}:{config.server.port}")
        
        # 设置日志
        setup_logging('INFO')
        
        # 异步连接测试
        async def async_test():
            scanner = await create_scanner(config.server)
            if scanner:
                return True, "连接成功"
            return False, "连接失败"
        
        success, message = asyncio.run(async_test())
        
        if success:
            typer.echo(f"✅ {message}")
        else:
            typer.echo(f"❌ {message}", err=True)
            raise typer.Exit(1)
            
    except FileNotFoundError:
        typer.echo("❌ 配置文件不存在，请先运行 'embytools init'", err=True)
        raise typer.Exit(1)
    except Exception as e:
        typer.echo(f"❌ 连接测试失败: {e}", err=True)
        raise typer.Exit(1)


@app.command()
def run(
    task_name: Optional[str] = typer.Option(
        None,
        help="指定任务名称，不指定则运行所有任务"
    ),
    dry_run: bool = typer.Option(
        False,
        help="干跑模式，只显示将要执行的操作"
    ),
    log_level: str = typer.Option(
        'INFO',
        help="日志级别: DEBUG, INFO, WARNING, ERROR"
    )
):
    """运行媒体库扫描任务"""
    try:
        config = config_manager.get_config()
        
        # 设置日志级别
        setup_logging(log_level)
        
        # 过滤任务
        if task_name:
            tasks = [t for t in config.tasks if t.name == task_name]
            if not tasks:
                typer.echo(f"❌ 未找到任务: {task_name}", err=True)
                raise typer.Exit(1)
        else:
            tasks = config.tasks
        
        typer.echo(f"🚀 开始执行 {len(tasks)} 个任务")
        
        # 异步执行任务
        async def async_run():
            scanner = await create_scanner(config.server)
            if not scanner:
                typer.echo("❌ 扫描器初始化失败", err=True)
                return False
            
            results = []
            for task in tasks:
                current_dry_run = dry_run or task.dry_run
                mode = "干跑模式" if current_dry_run else "执行模式"
                typer.echo(f"\n🎯 任务: {task.name} ({mode})")
                typer.echo(f"  播放列表: {task.playlist_name}")
                typer.echo(f"  媒体库: {', '.join(task.libraries)}")
                typer.echo(f"  规则: {task.rule}")
                
                # 执行任务
                result = await scanner.execute_task(task, current_dry_run)
                results.append(result)
                
                # 显示结果
                if result['success']:
                    if current_dry_run:
                        typer.echo(f"✅ 干跑完成: {result['message']}")
                    else:
                        typer.echo(f"✅ 执行完成: {result['message']}")
                else:
                    typer.echo(f"❌ 执行失败: {result.get('error', '未知错误')}", err=True)
            
            await scanner.close()
            return True
        
        success = asyncio.run(async_run())
        if success:
            typer.echo("\n🎉 所有任务执行完成")
        else:
            raise typer.Exit(1)
        
    except FileNotFoundError:
        typer.echo("❌ 配置文件不存在，请先运行 'embytools init'", err=True)
        raise typer.Exit(1)
    except Exception as e:
        typer.echo(f"❌ 执行失败: {e}", err=True)
        raise typer.Exit(1)


@app.command()
def version():
    """显示版本信息"""
    from . import __version__
    typer.echo(f"embytools 版本: {__version__}")


@app.command("export-douyin-json")
def export_douyin_json_command(
    library_name: str,
    output_file: str = "videos.json",
    max_videos: int = 100,
    emby_server: str = typer.Option(..., prompt="Emby服务器地址"),
    api_key: str = typer.Option(..., prompt="Emby API密钥")
):
    """
    导出Emby媒体库为抖音JSON格式
    """
    try:
        # 设置日志
        setup_logging('INFO')
        
        # 创建Emby客户端
        emby_client = create_emby_client_from_credentials(emby_server, api_key)
        
        # 测试连接
        if not asyncio.run(emby_client.test_connection()):
            typer.echo("❌ Emby服务器连接失败", err=True)
            raise typer.Exit(1)
        
        # 获取媒体库列表
        libraries = asyncio.run(emby_client.get_libraries())
        
        # 查找指定的媒体库
        target_library = None
        for lib in libraries:
            if lib['name'] == library_name:
                target_library = lib
                break
        
        if not target_library:
            typer.echo(f"❌ 未找到媒体库: {library_name}", err=True)
            raise typer.Exit(1)
        
        typer.echo(f"🎯 开始导出媒体库: {library_name} (ID: {target_library['id']})")
        typer.echo(f"📁 输出文件: {output_file}")
        typer.echo(f"🔢 最大导出数量: {max_videos}")
        
        # 执行导出
        videos = asyncio.run(export_emby_library_to_douyin_json(
            target_library['id'],
            target_library['name'],
            emby_server,
            api_key,
            max_videos
        ))
        
        # 保存为JSON文件
        output_path = Path(output_file)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(videos, f, ensure_ascii=False, indent=2)
        
        typer.echo(f"✅ 成功导出 {len(videos)} 个视频到 {output_path.absolute()}")
        
    except FileNotFoundError:
        typer.echo("❌ 配置文件不存在，请先运行 'embytools init'", err=True)
        raise typer.Exit(1)
    except Exception as e:
        typer.echo(f"❌ 导出失败: {e}", err=True)
        raise typer.Exit(1)


if __name__ == "__main__":
    app()